<template>
  <div class="channel-edit">
    <van-cell :border="false" class="my-channel-cell">
      <div class="my-channel-title" slot="title">我的频道</div>
      <van-button
        class="edit-btn"
        plain
        round
        size="mini"
        @click="handleCloseBtn"
      >{{ isShowCloseBtn ? '完成' : '编辑'}}
      </van-button>
    </van-cell>
    <van-grid class="my-grid" :gutter="15">
      <van-grid-item
        class="grid-item"
        v-for="(item, index) in myChannels"
        :key="item.id"
        @click="handleMyChannel(item, index)"
      >
        <span
          class="text"
          :class="{active: index === active}"
          slot="text"
        >{{item.name}}</span>
        <van-icon
          slot="icon"
          name="close"
          v-show="isShowCloseBtn && (item.id !== 0)"
        ></van-icon>
      </van-grid-item>
    </van-grid>

    <van-cell :border="false" class="recom-channel-cell">
      <div class="recom-channel-title" slot="title">频道推荐</div>
    </van-cell>
    <van-grid class="recom-grid" :gutter="15">
      <van-grid-item
        v-for="(item, index) in getRecomChannels"
        :key="index"
        class="grid-item"
        :border="false"
        icon="plus"
        :text="item.name"
        @click="onAddToMyChannel(item)"
      />
    </van-grid>
  </div>
</template>

<script>
import { getAllChannels, addUserChannels, deleteUserChannels } from '@/api/channel'
import { mapState } from 'vuex'
import { setItem } from '@/utils/storage'
export default {
  name: 'ChannelEdit',
  props: {
    myChannels: {
      type: Array,
      required: true
    },
    active: { // 用于控制频道编辑页的高亮
      type: Number,
      required: true
    }
  },
  data () {
    return {
      allChannels: [],
      isShowCloseBtn: false // 控制关闭按钮的显示隐藏
    }
  },
  computed: {
    ...mapState(['user']),
    getRecomChannels () {
      const arr = []
      this.allChannels.forEach((item) => {
        // find找到（第一个）就返回这个值，找不到返回undefined
        const flag = this.myChannels.find((value) => {
          return item.id === value.id
        })
        if (!flag) { // 在我的频道中找不到，说明是目标值
          arr.push(item)
        }
      })
      return arr
    }
  },
  methods: {
    async loadAllChannels () {
      try {
        const { data } = await getAllChannels()
        this.allChannels = data.data.channels
      } catch (err) {
        this.$toast('获取列表数据失败')
      }
    },
    async keepMyChannels (channel, handle) {
      if (this.user) { // 已登录，存在后端
        if (handle === 'add') { // 增加频道
          try {
            await addUserChannels({
              id: channel.id,
              seq: this.myChannels.length
            })
          } catch (err) {
            this.$toast('添加用户频道失败')
          }
        } else if (handle === 'delete') {
          try {
            await deleteUserChannels(channel.id)
          } catch (err) {
            this.$toast('删除用户频道失败')
          }
        }
      } else { // 未登录，存在本地
        setItem('UNLOGIN_CHANNELS', this.myChannels)
      }
    },
    async onAddToMyChannel (channel) {
      this.myChannels.push(channel)
      // 数据持久化处理
      this.keepMyChannels(channel, 'add')
    },
    handleCloseBtn () {
      this.isShowCloseBtn = !this.isShowCloseBtn
    },
    handleMyChannel (channel, index) {
      if (!this.isShowCloseBtn) { // 非编辑：没有关闭按钮时点击频道只切换(通过active)
        this.$emit('updateActive', index, false) // false不展示弹层
      } else { // 编辑状态
        if (channel.id !== 0) { // “推荐”不能删
          this.myChannels.splice(index, 1)
          // 数据持久化处理
          this.keepMyChannels(channel, 'delete')
          // 删除active之前的频道，当前激活的会改变
          // 解决方法
          if (index <= this.active) {
            this.$emit('updateActive', this.active - 1, true)
          }
        } else {
          this.$toast('默认频道不能删')
        }
      }
    }
  },
  created () {
    this.loadAllChannels()
  }
}
</script>

<style scoped lang="less">
  .channel-edit {
    padding: 90px 0;
    /deep/ .grid-item {  // 公共样式
      width: 160px;
      height: 86px;
      .van-grid-item__content {
        background-color: #f4f5f6;
        .van-grid-item__text, .text {
          font-size: 28px;
          color: #222;
        }
        .active {
          color: red;
        }
      }
    }
    .my-channel-cell {
      .my-channel-title {
        font-size: 32px;
        color: #333333;
      }
      .edit-btn {
        width: 104px;
        line-height: 48px;
        font-style: 30px;
        color: #f85959;
        border-color: #f85959;
      }
    }
      /deep/ .my-grid {
      .grid-item {
        margin: 0;
        .van-grid-item__icon-wrapper {
          position: unset;
        }
        .van-icon-close {
          position: absolute;
          top: -8px;
          right: -8px;
          font-size: 30px;
        }
        .van-grid-item__text {
          margin-top: 0;
        }
      }
    }
    .recom-channel-cell {
      margin-top: 30px;
      .recom-channel-title {
        font-size: 32px;
        color: #333333;
      }
    }
    /deep/ .recom-grid {
      .grid-item {
        .van-grid-item__content {
          white-space: nowrap;
          flex-direction: row;
        }
        .van-icon-plus {
          margin-right: 5px;
          font-size: 30px;
          color: #222222;
        }
        .van-grid-item__text {
          margin-top: 0;
        }
      }
    }
  }
  .van-popup__close-icon {
    margin-top: 20px;
  }
</style>
